<?php
namespace app\farm\controller;
use app\ApiRest;

use app\farm\model\Breed;
use app\farm\model\BreedOrder;
use app\farm\model\Claim;
use app\farm\model\ClaimOrder;
use app\farm\model\ClaimText;
use app\farm\model\Config;
use app\farm\model\Evaluate;
use app\farm\model\FinanceWater;
use app\farm\model\Goods;
use app\farm\model\GoodsCate;
use app\farm\model\GoodsSh;
use app\farm\model\LandCate;
use app\farm\model\LandList;
use app\farm\model\LandOrder;
use app\farm\model\LandSourceText;
use app\farm\model\LandSpe;
use app\farm\model\LandText;
use app\farm\model\Machine;
use app\farm\model\Massif;

use app\farm\model\Address;

use app\farm\model\Farmer;
use app\farm\model\Monitor;
use app\farm\model\MonitorText;
use app\farm\model\Seed;
use app\farm\model\SendOrder;
use app\farm\model\ShopGoods;
use app\farm\model\ShopGoodsCate;
use app\farm\model\ShopGoodsSh;
use app\farm\model\ShopOrder;
use app\farm\model\Source;
use app\farm\model\SourceText;
use app\farm\model\User;
use app\farm\model\Wallet;
use app\farm\model\ShopRefund;
use longbingcore\wxcore\WxSetting;
use think\App;
use think\facade\Db;
use think\Request;


class IndexStore extends ApiRest
{

    protected $model;

    protected $address_model;

    protected $massif_model;

    protected $land_model;

    protected $user_model;

    public function __construct(App $app) {

        parent::__construct($app);

        $this->model = new Farmer();

        $this->user_model  = new User();

        $dis = [

            'type'   => 2,

            'status' => 2,

            'user_id'=> $this->getUserId()
        ];

        $this->store = $this->model->dataInfo($dis);

        if(empty($this->store)){

            $this->errorMsg('你还不是地主');
        }

        $this->address_model = new Address();

        $this->land_model    = new LandList();

        $this->massif_model  = new Massif();

    }


    /**
     * @author chenniang
     * @DataTime: 2022-02-22 13:53
     * @功能说明:店铺详情
     */
    public function storeInfo(){

        return $this->success($this->store);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-02-22 13:54
     * @功能说明:修改店铺
     */
    public function storeUpdate(){

        $input = $this->_input;

        $dis = [

            'id' => $this->store['id']
        ];

        $res = $this->model->dataUpdate($dis,$input);

        return $this->success($res);

    }



    /**
     * @author chenniang
     * @DataTime: 2021-03-23 09:34
     * @功能说明:商品分类列表
     */
    public function goodsCateList(){

        $cate_model = new ShopGoodsCate();

        $dis[] = ['uniacid','=',$this->_uniacid];

        $dis[] = ['status','>',-1];

        $dis[] = ['store_id','=',$this->store['id']];

        $data = $cate_model->dataList($dis,20);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-23 10:03
     * @功能说明:添加商品分类
     */
    public function goodsCateAdd(){

        $input = $this->_input;

        $input['uniacid'] = $this->_uniacid;

        $input['store_id'] = $this->store['id'];

        $cate_model = new ShopGoodsCate();

        $res = $cate_model->dataAdd($input);

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-23 10:06
     * @功能说明:编辑商品分类
     */
    public function goodsCateUpdate(){

        $input = $this->_input;

        $dis = [

            'id' => $input['id']
        ];

        $cate_model = new ShopGoodsCate();

        $cate_info  = $cate_model->dataInfo($dis);

        if(empty($cate_info)){

            $this->errorMsg('商品分类不存在');
        }
        //如果是删除
        if(!empty($input['status'])&&$input['status']==-1&&$cate_info['goods_num']>0){

            $this->errorMsg('该分类下存在商品，无法删除');

        }

        $res = $cate_model->dataUpdate($dis,$input);

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-23 10:08
     * @功能说明:商品分类下拉框
     */
    public function goodsCateSelect(){

        $cate_model = new ShopGoodsCate();

        $dis[] = ['uniacid','=',$this->_uniacid];

        $dis[] = ['status','=',1];

        $dis[] = ['store_id','=',$this->store['id']];

        $data = $cate_model->where($dis)->where('top desc,id desc')->select()->toArray();

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-23 15:06
     * @功能说明:商品各个状态下的数量
     */
    public function goodsCount(){

        $dis = [

            'uniacid' => $this->_uniacid,

            'store_id'  => $this->store['id'],

            'status'  => 1

        ];

        $goods_model = new ShopGoods();
        //上架数量
        $data['on_count']    = $goods_model->where($dis)->count();

        $dis['status'] = 2;
        //下架数量
        $data['off_count']   = $goods_model->where($dis)->count();

        $dis['status'] = 3;
        //仓库数量
        $data['house_count'] = $goods_model->where($dis)->count();

        return $this->success($data);


    }




    /**
     * @author chenniang
     * @DataTime: 2021-03-23 11:08
     * @功能说明:商品列表
     */
    public function goodsList(){

        $input = $this->_param;

        $dis[] = ['uniacid','=',$this->_uniacid];

        $dis[] = ['store_id','=',$this->store['id']];

        $dis[] = ['status','=',$input['status']];
        //商品名字搜索
        if(!empty($input['goods_name'])){

            $dis[] = ['goods_name','like','%'.$input['goods_name'].'%'];
        }

        $goods_model = new ShopGoods();

        $data = $goods_model->dataList($dis,10);

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){
                //创建时间
                $v['create_time'] = date('Y/m/d',$v['create_time']);

            }

        }

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-03-01 10:44
     * @功能说明:商品详情
     */
    public function goodsInfo(){

        $input = $this->_param;

        $dis = [

            'id' => $input['id']
        ];

        $goods_model = new ShopGoods();

        $data = $goods_model->dataInfo($dis);

        $farmer_model = new Farmer();

        $source_model = new Source();

        $cate_model   = new ShopGoodsCate();

        $data['farmer_title'] = $farmer_model->where(['id'=>$data['farmer_id']])->value('title');

        $data['source_title'] = $source_model->where(['id'=>$data['source_id']])->value('title');

        $data['cate_title']   = $cate_model->where(['id'=>$data['cate_id']])->value('title');

        return $this->success($data);

    }

    /**
     * @author chenniang
     * @DataTime: 2021-03-23 09:32
     * @功能说明:添加商品
     */
    public function goodsAdd(){

        $input = $this->_input;
        //0放入仓库 1提交审核
       // $type  = !empty($input['type'])?$input['type']:0;

        unset($input['type']);

        $input['uniacid'] = $this->_uniacid;

        $input['store_id']= $this->store['id'];

        $input['user_id'] = $this->getUserId();

        $input['imgs']    = !empty($input['imgs'])?implode(',',$input['imgs']):'';

        $core  = new WxSetting($this->_uniacid);

        if(!empty($input['goods_name'])){

            $rest  = $core->wxContentRlue($input['goods_name']);

            if($rest['errcode'] != 0){

                return $this->error('标题含有违法违规内容');
            }

        }


        if(!empty($input['text'])){

            $input['text'] = serialize($input['text']);
        }

//        if(!empty($input['text'])){
//
//            $rest  = $core->wxContentRlue($input['text']);
//
//            if($rest['errcode'] != 0){
//
//                return $this->error('标题含有违法违规内容');
//            }
//
//        }

        $goods_model = new ShopGoods();

        $id = $goods_model->dataAdd($input);

        return $this->success(1);
    }


    /**
     * @author chenniang
     * @DataTime: 2022-02-25 17:49
     * @功能说明:编辑商品
     */
    public function goodsUpdate(){

        $input = $this->_input;

        $dis = [

            'id' => $input['id']
        ];

        $core  = new WxSetting($this->_uniacid);

        if(!empty($input['goods_name'])){

            $rest  = $core->wxContentRlue($input['goods_name']);

            if($rest['errcode'] != 0){

                return $this->error('标题含有违法违规内容');
            }

        }

//        if(!empty($input['text'])){
//
//            $rest  = $core->wxContentRlue($input['text']);
//
//            if($rest['errcode'] != 0){
//
//                return $this->error('标题含有违法违规内容');
//            }
//
//        }

        if(!empty($input['text'])){

            $input['text'] = serialize($input['text']);
        }

        if(isset($input['imgs'])){

            $input['imgs'] = !empty($input['imgs'])?implode(',',$input['imgs']):'';
        }

        $goods_model = new ShopGoods();

        $input['uniacid'] = $this->_uniacid;

        $res = $goods_model->goodsUpdate($dis,$input);

        return $this->success($res);
    }


    /**
     * @author chenniang
     * @DataTime: 2022-03-01 11:44
     * @功能说明:商品上下家删除
     */
    public function goodsStatusUpdate(){

        $input = $this->_input;

        $goods_model = new ShopGoods();

        $dis = [

            'id' => $input['id']
        ];

        $res = $goods_model->dataUpdate($dis,['status'=>$input['status']]);

        return $this->success($res);

    }

    /**
     * @param $input
     * @功能说明:提交审核方法
     * @author chenniang
     * @DataTime: 2021-03-23 14:27
     */
    public function subGoodsShAction($goods_id){

        $insert = [

            'uniacid' => $this->_uniacid,

            'user_id' => $this->getUserId(),

            'cap_id'  => $this->cap_info['id'],

            'order_code' => orderCode(),

            'status'     => 1,

        ];

        $goods_sh_model = new ShopGoodsSh();

        $goods_sh_model->dataAdd($insert);

        $id = $goods_sh_model->getLastInsID();
        //提交审核
        $res = $goods_sh_model->subSh($id,$goods_id);

        if(!empty($res['code'])){

            $this->errorMsg($res['msg']);
        }

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-23 11:31
     * @功能说明:商品批量上下架
     */
    public function someGoodsUpdate(){

        $input = $this->_input;

        $goods_model = new ShopGoods();
        //全选
        if(!empty($input['all'])){

            $res = $goods_model->where(['store_id'=>$this->store['id'],'status'=>$input['now_status']])->where('status','>',-1)->update(['status'=>$input['status']]);

        }else{

            $res = $goods_model->where('id','in',$input['goods_id'])->update(['status'=>$input['status']]);
        }

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-02-28 14:08
     * @功能说明:添加商品时农场主下拉框
     */
    public function goodsFarmerSelect(){

        $input = $this->_param;

        $order_farmer = $this->model->goodsFarmerSelect($this->getUserId());

        $map[] = ['id','in',$order_farmer];

        $map[] = ['status','in',[2,3]];

        $map[] = ['type','=',1];

        $list  = $this->model->where($map)->field('id,title')->select()->toArray();

        return $this->success($list);
    }




    /**
     * @author chenniang
     * @DataTime: 2022-02-28 14:22
     * @功能说明:添加商品时溯源下拉框
     */
    public function goodsSourceSelect(){

        $input = $this->_param;

        $land_order_model = new LandOrder();

        $source_model = new Source();

        $id = $land_order_model->goodsSourceSelect($this->getUserId());

        $map[] = ['id','in',$id];

        $map[] = ['status','=',1];

        $list = $source_model->where($map)->field('id,title')->order('id desc')->select()->toArray();

        return $this->success($list);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-03-01 11:03
     * @功能说明:订单列表
     */
    public function orderList(){

        $input = $this->_param;

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        $dis[] = ['a.store_id','=',$this->store['id']];

        $where = [];

        if(!empty($input['name'])){

            $where[] = ['b.goods_name','like','%'.$input['name'].'%'];

            $where[] = ['a.order_code','like','%'.$input['name'].'%'];

        }

        if(!empty($input['pay_type'])){

            $dis[] = ['a.pay_type','=',$input['pay_type']];

        }else{

            $dis[] = ['a.pay_type','>=',1];

        }

        $order_model = new ShopOrder();

        $data = $order_model->indexDataList($dis,$where);

        $arr = [
            'no_pay_count'   => 1,
            //未发货
            'no_send_count'  => 2,
            //已经发货
            'have_send_count'=> 3
        ];

        foreach ($arr as $ks=>$vs){

            $map = [

                'store_id'=> $this->store['id'],

                'pay_type'=> $vs
            ];

            $data[$ks] = $order_model->where($map)->count();
        }

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-03-07 10:31
     * @功能说明:分配订单给农场主
     */
    public function distributionOrderFarmer(){

        $input = $this->_input;

        $order_model = new ShopOrder();

        $dis = [

          'id' => $input['id']
        ];

        $refund_model = new ShopRefund();
        //判断有无申请中的退款订单
        $refund_order = $refund_model->dataInfo(['order_id'=>$input['id'],'status'=>1]);

        if(!empty($refund_order)){

            $this->errorMsg('该订单正在申请退款，请先处理再核销');

        }

        $res = $order_model->dataUpdate($dis,['farmer_show'=>1]);

        return $this->success($res);


    }



    /**
     * @author chenniang
     * @DataTime: 2021-03-15 14:58
     * @功能说明:订单详情
     */
    public function orderInfo(){

        $input = $this->_param;

        $order_model = new ShopOrder();

        $dis = [

            'id' => $input['id']
        ];

        $data = $order_model->dataInfo($dis);

        $data['over_time'] -= time();

        $time_arr = ['create_time','pay_time','end_time','hx_time','over_time','cancel_time'];

        foreach ($time_arr as $v){

            $data[$v] = !empty($data[$v])?date('Y-m-d H:i:s',$data[$v]):$data[$v];

        }

        $data['distance'] = distance_text($data['distance']);
        //配送时间
        $data['user_send_time'] = date('Y-m-d H:i',$data['send_start_time']).'~'.date('H:i',$data['send_end_time']);

        $farmer_model = new Farmer();

        $data['farmer_info'] = $farmer_model->dataInfo(['id'=>$data['farmer_id']],'title');

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-19 17:29
     * @功能说明:退款订单详情
     *
     */
    public function refundOrderList(){

        $input = $this->_param;

        $refund_model = new ShopRefund();

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        $dis[] = ['a.store_id','=',$this->store['id']];

        $where = [];

        if(!empty($input['name'])){

            $where[] = ['b.goods_name','like','%'.$input['name'].'%'];

            $where[] = ['a.order_code','like','%'.$input['name'].'%'];

        }

        if(!empty($input['status'])){

            $dis[] = ['a.status','=',$input['status']];

        }else{

            $dis[] = ['a.status','>',-1];

        }

        $data = $refund_model->indexDataList($dis,$where);

        $map = [

            'status'  => 1,

            'store_id'=> $this->store['id']
        ];
        //退款中数量
        $data['ing_count'] = $refund_model->where($map)->count();

        return $this->success($data);


    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-18 09:21
     * @功能说明:拒绝退款
     */
    public function noPassRefund(){

        $input = $this->_input;

        $refund_order_model = new ShopRefund();

        $res = $refund_order_model->noPassRefund($input['id'],$this->getUserId());

        if(!empty($res['code'])){

            $this->errorMsg($res['msg']);
        }

        return $this->success($res);

    }


    /**\
     * @author chenniang
     * @DataTime: 2021-03-18 09:28
     * @功能说明:同意退款
     */
    public function passRefund(){

        $input = $this->_input;

        $refund_order_model = new ShopRefund();

        $res = $refund_order_model->passOrder($input['id'],$input['price'],$this->payConfig(),$this->getUserId(),$input['text']);

        if(!empty($res['code'])){

            $this->errorMsg($res['msg']);
        }

        return $this->success($res);

    }

    /**
     * @author chenniang
     * @DataTime: 2021-03-19 17:50
     * @功能说明:退款订单详情
     */
    public function refundOrderInfo(){

        $input = $this->_param;

        $dis = [

            'id' => $input['id']
        ];

        $refund_order_model = new ShopRefund();

        $data = $refund_order_model->dataInfo($dis);

        $order_model = new ShopOrder();

        $data['pay_order_code'] = $order_model->where(['id'=>$data['order_id']])->value('order_code');

        $data['create_time'] = date('Y-m-d H:i:s',$data['create_time']);

        $data['refund_time'] = date('Y-m-d H:i:s',$data['refund_time']);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-12-30 11:15
     * @功能说明:申请提现
     */
    public function applyWallet(){

        $input = $this->_input;

        $wallet_model = new Wallet();

        $config_model = new Config();

        $user   = $this->user_model->dataInfo(['id'=>$this->getUserId()]);

        $config = $config_model->dataInfo(['uniacid'=>$this->_uniacid]);

        if($input['apply_price']>$user['wallet_cash']){

            $this->errorMsg('余额不足');
        }

        Db::startTrans();

        $insert = [

            'uniacid'    => $this->_uniacid,

            'user_id'    => $this->getUserId(),

            'order_code' => orderCode(),

            'store_id'   => $this->store['id'],

            'pay_price'  => $input['apply_price'],

            'text'       => $input['text'],

            'true_price' => round($input['apply_price']*$config['cash_balance']/100,2),

            'balance'    => $config['cash_balance'],

            'type'       => 2,
        ];
        //发起提现
        $res = $wallet_model->dataAdd($insert);

        if($res==0){

            Db::rollback();

            $this->errorMsg('申请失败');

        }

        $water_model = new FinanceWater();

        $id = $wallet_model->getLastInsID();
        //添加提现记录
        $res = $water_model->addWater($id,15,2,1);

        if($res==0){

            Db::rollback();

            $this->errorMsg('申请失败');

        }

        $id  = $water_model->getLastInsID();
        //执行记录
        $res = $water_model->cashArrival(0,0,$id);

        if($res==0){

            Db::rollback();

            $this->errorMsg('申请失败');

        }

        Db::commit();

        return $this->success($res);

    }
















}
